<template>
  <div class="user-container">
    <el-card>
      <div class="user-container-header">
        <div class="user-container-header-left">
          <el-button type="primary" :icon="Plus" @click="handleAdd">添加</el-button>
          <el-button type="danger" :icon="Delete" @click="handleAllDelte">批量删除</el-button>
        </div>
        <div class="user-container-header-right">
          <el-input v-model="search" placeholder="请输入用户名" type="search" />
          <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
        </div>
      </div>
      <!-- 表格  -->
      <Table
        :tableData="tableData"
        :columns="columns"
        @edit="handleEdit"
        @delete="handleDelete"
        @selection-change="handleAllChange"
      />
      <!-- 分页 -->
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="currentPageSize"
          :page-sizes="[10, 20, 30, 40]"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
      <!-- 添加用户 || 编辑用户-->
      <el-dialog v-model="addDialogVisible" :title="addForm.id ? '编辑' : '添加'" width="35%">
        <el-form :model="addForm" label-width="120px" class="add-form" :rules="addFormRules">
          <el-form-item label="用户名" prop="name">
            <el-input v-model="addForm.name" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email" />
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-select v-model="addForm.role" placeholder="请选择角色">
              <el-option label="管理员" value="admin" />
              <el-option label="用户" value="user" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addForm.id ? handleSave() : handleAdd()">
            {{ addForm.id ? "保存" : "添加" }}
          </el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import Table from "@/components/reuse/table.vue";
import https from "@/utils/https";
import { Search, Plus, Delete, Edit } from "@element-plus/icons-vue";
import { ref, onMounted, reactive, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
// 第几页
const currentPage = ref<number>(1);
// 每页条数
const currentPageSize = ref<number>(10);
// 是否禁用
const disabled = ref(false);
// 是否显示背景
const background = ref(true);
// 搜索
const search = ref("");
const total = ref<number>(0); // 确保是 ref
const addDialogVisible = ref<boolean>(false);
// 添加表单
const addForm = reactive({
  id: "",
  name: "",
  password: "",
  email: "",
  role: "",
});
const addFormRules = reactive({
  name: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9\u4e00-\u9fa5]+$/,
      message: "用户名只能包含字母、数字、汉字",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur", min: 6, max: 16 },
    {
      pattern: /^[a-zA-Z0-9]+$/,
      message: "密码只能包含字母和数字",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: "请输入正确的邮箱格式",
      trigger: "blur",
    },
  ],
  role: [{ required: true, message: "请选择角色", trigger: "blur" }],
});
// 全选数组
const allArr = ref<any[]>([]);
// 表格数据初始化
const tableData = reactive([
  {
    id: 1,
    name: "张三",
    email: "123456@qq.com",
    role: "admin",
    updateTime: "2024-01-01",
  },
]);
// 分页
const columns = ref([
  { label: "用户名", prop: "name" },
  { label: "邮箱", prop: "email" },
  { label: "更新时间", prop: "updateTime" },
]);
// 初始化
onMounted(() => {
  getPages();
  getTableData();
});
// 改版复选
const handleAllChange = (val: any[]) => {
  allArr.value = val;
  console.log("选中的数据:", allArr.value); // 调试用
};

// 批量删除
const handleAllDelte = () => {
  if (!allArr.value || allArr.value.length === 0) {
    ElMessage.warning("请先选择要删除的数据");
    return;
  }

  ElMessageBox.confirm("您确定要删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      const res = await https.delete("/table/all", {
        data: {
          ids: allArr.value,
        },
      });

      if (res.code === 200) {
        ElMessage.success("删除成功");
        allArr.value = [];
        tableData.length = 0;
      } else {
        ElMessage.error(res.message || "删除失败");
      }
    } catch (error) {
      console.error("删除错误:", error);
      ElMessage.error("删除失败");
    }
  });
};
// 搜索
const handleSearch = () => {
  for (let i = 0; i < tableData.length; i++) {
    if (tableData[i].name.includes(search.value)) {
      currentPage.value = 1;
      getTableData();
    }
  }
  search.value = "";
};
// 分页改变处理
const handlePageChange = (val: number) => {
  currentPage.value = val;
  getTableData();
};

// 每页条数改变处

const handleSizeChange = (val: number) => {
  currentPageSize.value = val;
  getTableData();
};

// 表格数据获取 分页
const getTableData = async () => {
  const res = await https.get(`/table`, {
    params: {
      currentPage: currentPage.value,
      pageSize: currentPageSize.value,
    },
  });
  const { list, page, total: totalCount, pageSize } = res;
  tableData.length = 0;
  list.forEach((item: any) => {
    tableData.push({
      id: item.id,
      name: item.name,
      email: item.email,
      role: item.role,
      updateTime: item.updateTime,
    });
  });

  currentPage.value = page;
  currentPageSize.value = pageSize;
  total.value = totalCount;
  console.log(res);
};

// 获取分页数据
const getPages = async () => {
  const res = await https.post(`/pages`, {
    currentPage: currentPage.value,
    currentPageSize: currentPageSize.value,
  });
  console.log(res);
};
// 编辑
const handleEdit = async (row: any) => {
  addDialogVisible.value = true;
  // 填充表单数据
  Object.assign(addForm, {
    id: row.id,
    name: row.name,
    email: row.email,
    role: row.role,
    password: row.password || "",
  });
};

// 修改保存按钮的处理方法
const handleSave = async () => {
  try {
    const res = await https.put("/table/put", {
      id: addForm.id,
      data: {
        name: addForm.name,
        email: addForm.email,
        role: addForm.role,
        password: addForm.password,
      },
    });

    if (res.code === 200) {
      ElMessage.success("更新成功");
      addDialogVisible.value = false;
      getTableData();
      // 清空表单
      Object.assign(addForm, {
        id: "",
        name: "",
        email: "",
        role: "",
        password: "",
      });
    } else {
      ElMessage.error(res.message || "更新失败");
    }
  } catch (error) {
    console.error("更新错误:", error);
    ElMessage.error("更新失败");
  }
};

// 删除
const handleDelete = async (row: any) => {
  await ElMessageBox.confirm("确定要删除该用户吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  });

  const res = await https.delete("/table", {
    data: { id: row.id },
  });

  if (res.code === 200) {
    ElMessage.success("删除成功");
    getTableData();
  } else {
    ElMessage.error(res.message || "删除失败");
  }
};

// 添加
const handleAdd = async () => {
  addDialogVisible.value = !addDialogVisible.value;
  const res = await https.post("/table/add", addForm);
  if (res.code === 200) {
    ElMessage({
      message: "添加成功",
      type: "success",
    });
    // 获取表格数据
    addDialogVisible.value = false;
    getTableData();
    Object.assign(addForm, {
      name: "",
      password: "",
      email: "",
      role: "",
    });
    // 清空表单
  } else {
    ElMessage({
      message: "添加失败",
      type: "error",
    });
  }
};
</script>

<style scoped>
.user-container {
  padding: 20px;
  height: 100%;
}

.user-card {
  background: rgba(255, 255, 255, 0.1) !important;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1) !important;
}

.user-container-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 24px;
}

.user-container-header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}
.add-form {
  width: 400px;
}

.user-container-header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 表格样式 */
.user-container-table {
  margin-top: 20px;
}
.user-container-table-edit {
  display: flex;
  justify-content: center;
  gap: 30px;
}
.user-container-table-edit :nth-child(1) {
  color: #409eff;
}
.user-container-table-edit :nth-child(2) {
  color: #f56c6c;
}
.user-container-table-edit div {
  cursor: pointer;
}
.user-container-table-edit div:hover {
  text-decoration: underline;
}
:deep(.table-header) {
  background: rgba(255, 255, 255, 0.1) !important;
  color: #ffffff !important;
  font-weight: 500;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

:deep(.table-row) {
  background: transparent !important;
  color: rgba(255, 255, 255, 0.9) !important;
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);
  transition: all 0.3s ease;
}

:deep(.table-row:hover) {
  background: rgba(255, 255, 255, 0.05) !important;
}

:deep(.el-table) {
  background: transparent !important;
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
}

:deep(.el-table__inner-wrapper::before) {
  display: none;
}

:deep(.el-table__cell) {
  background: transparent !important;
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}

/* 操作按钮样式 */
.table-actions {
  display: flex;
  justify-content: center;
  gap: 16px;
}

:deep(.el-button.is-link) {
  color: rgba(255, 255, 255, 0.9) !important;
}

:deep(.el-button.is-link:hover) {
  color: #ffffff !important;
  transform: translateY(-2px);
}

:deep(.el-button.is-link.is-link--danger:hover) {
  color: #f56c6c !important;
}

/* Tag样式 */
:deep(.el-tag) {
  background: transparent !important;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

:deep(.el-tag--primary) {
  color: #409eff !important;
  border-color: #409eff;
}

:deep(.el-tag--warning) {
  color: #e6a23c !important;
  border-color: #e6a23c;
}

/* 分页样式 */
.demo-pagination-block {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

:deep(.el-pagination) {
  background: transparent !important;
}

:deep(.el-pagination .el-pagination__total, .el-pagination .el-pagination__jump) {
  color: rgba(255, 255, 255, 0.8) !important;
}
</style>
